package com.shopping.mall.base.util;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Setter
@ConfigurationProperties(prefix = "oss")
public class OSSUtils {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 上传文件
     */
    public String uploadFile(InputStream inputStream, String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传网络流。
        ossClient.putObject(bucketName, objectName, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();
        return "https://" + bucketName + "." + endpoint + "/" + objectName;
    }

    public Map<String,Object> getSignature(String ossDir) throws UnsupportedEncodingException {
        //1、授权OSS存储路径：imgs 或者 imgs/headpic，因为签名授权的时候需要指定授权的OSS存储路径
        String tmpDir = ossDir;

        //2、配置签名所需数据：从阿里云OSS控制台获取
        //OSS控制台获取 开通OSS服务后创建一个名为xxx的Bucket：参考尾部附图


        //3、初始化OSS客户端
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //4、生成签名
        int tmpExpireSeconds = 100;//有效截止时间 根据自己业务需求随便给
        Date tmpExpireTime = DateUtil.offsetSecond(DateUtil.date(),tmpExpireSeconds);
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0L, 1048576000L);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, ossDir);

        String postPolicy = client.generatePostPolicy(tmpExpireTime, policyConds);
        byte[] binaryData = postPolicy.getBytes("utf-8");

        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = client.calculatePostSignature(postPolicy);

//        String encodedPolicy = DatatypeConverter.printBase64Binary(binaryData);
//        byte[] s = SecureUtil.hmacSha1(accessKeySecret).digest(encodedPolicy);
//        String signature = DatatypeConverter.printBase64Binary(s);

        Map<String,Object> map=new HashMap<>();
        map.put("AccessKeyId",accessKeyId);
        map.put("Policy",encodedPolicy);
        map.put("Signature",postSignature);
        map.put("Host",endpoint);
        map.put("BucketName",bucketName);
        map.put("ExpireTime",tmpExpireSeconds);

        //5、返回签名内容:此处简单返回一个匿名类
        return map;
    }
}